import fetch from 'dva/fetch';
import merge from 'lodash/merge';

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}


function PreprocessingData(res){
  let data = res.data
  var defaults = {
    't': new Date().getTime(),
    'type': res.method === 'GET' ? 'develop' : ''
  }
  data = merge(defaults, data)
  return JSON.stringify(data)
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, options) {
  let init = {}
  if(options.method === 'POST'){
    init ={
      method:options.method,
      body:PreprocessingData(options),
      headers: new Headers({
        'Content-Type': 'application/json; charset=utf-8'
      })
    }
  }else{
    init = {
      method:'GET',
      headers: new Headers({
        'Content-Type': 'application/json; charset=utf-8'
      })
    }
    let paramsArray = [];
    Object.keys(options.data).forEach(key => paramsArray.push(key + '=' + options.data[key]))  
    if (url.search(/\?/) === -1) {  
        url += '?' + paramsArray.join('&')  
    } else {  
        url += '&' + paramsArray.join('&')  
    }
  }
  return fetch(url,init)
  .then(checkStatus)
  .then(parseJSON)
  .then(data => data )
  .catch(err => err );
}
